package com.orangelife.mobile.address.activity;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.common.sp.ShoppingSp;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.address.entity.AddressBean;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.zoning.activity.SelectZoningActicity;

import java.util.HashMap;
import java.util.Map;

public class EditAddressActivity extends OrangeLifeBaseActivity {

    private EditText username;
    private EditText phone;
    private TextView province;
    private EditText address;
    private Button btnDefault;
    private LinearLayout ll;
    private TextView title;
    private String addressID;
    private String isDefault;
    private LinearLayout zoning = null;
    private String mprovince = null;
    private String mcity = null;
    private String mdistrict = null;
    private LinearLayout lldelete = null;
    private Map<String, Object> map = null;
    private Dialog dlgLoading;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_edit);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        map = (Map<String, Object>) bundle.getSerializable("listmap");
        initView();
        findView();
    }

    private void initView() {
        username = (EditText) findViewById(R.id.et_username);
        phone = (EditText) findViewById(R.id.et_phone);
        province = (TextView) findViewById(R.id.et_province);
        address = (EditText) findViewById(R.id.et_address);
        ll = (LinearLayout) findViewById(R.id.ll_score);
        lldelete = (LinearLayout) findViewById(R.id.ll_delete);
        title = (TextView) findViewById(R.id.tv_title);
        zoning = (LinearLayout) findViewById(R.id.ll_zoning);
        btnDefault = (Button) findViewById(R.id.btnDefault);
    }

    private void findView() {
        ll.setVisibility(View.INVISIBLE);
        title.setText("我的地址");
        zoning.setOnClickListener(onclickListener);
        lldelete.setOnClickListener(onclickListener);
        if (map != null) {
            addressID = map.get("addressID").toString();
            mprovince = map.get("province").toString();
            mcity = map.get("city").toString();
            mdistrict = map.get("district").toString();
            username.setText(map.get("consignee").toString());
            phone.setText(map.get("phone").toString());
            province.setText(mprovince + mcity + mdistrict);
            address.setText(map.get("address").toString());
            isDefault = map.get("isDefault").toString();
            if ("1".equals(isDefault)) {
                btnDefault.setVisibility(View.GONE);
            } else {
                btnDefault.setVisibility(View.VISIBLE);
            }
            ShoppingSp.setTradePhone(phone.getText().toString());
        }
    }

    View.OnClickListener onclickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_zoning:
                    Intent intent = new Intent();
                    intent.setClass(EditAddressActivity.this, SelectZoningActicity.class);
                    startActivityForResult(intent, 1);
                    break;
                case R.id.ll_delete:
                    dialog(addressID);
                    break;
                default:
                    break;
            }
        }
    };

    @SuppressWarnings("unchecked")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                if (data != null) {
                    Map<String, Object> map = (Map<String, Object>) data.getSerializableExtra("zoning");
                    mprovince = map.get("province").toString();
                    mcity = map.get("city").toString();
                    mdistrict = map.get("district").toString();
                    province.setText(mprovince + mcity + mdistrict);
                }
                break;

            default:
                break;
        }
    }


    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 500:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    DialogHelper.closeDialog(dlgLoading);
                    break;
                case 1011:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    isLogin(dlgLoading);
                    break;
                case 1:
                    ToastHelper.getInstance()._toast(getResources().getString(R.string.complaintes_save_success));
                    ShoppingSp.clearTradeAddressInfo();
                    DialogHelper.closeDialog(dlgLoading);
                    finish();
                    break;
                case 3:
                    ToastHelper.getInstance()._toast("删除成功");
                    DialogHelper.closeDialog(dlgLoading);
                    finish();
                    break;
                default:
                    break;
            }
        }

    };

    public void edit(View view) {
        if ("".equals(username.getText().toString())) {
            ToastHelper.getInstance()._toast("请填写联系人");
            return;
        } else if ("".equals(phone.getText().toString())) {
            ToastHelper.getInstance()._toast("请填写联系电话");
            return;
        } else if ("".equals(mprovince)) {
            ToastHelper.getInstance()._toast("请填选择收货城市");
            return;
        } else if ("".equals(address.getText().toString())) {
            ToastHelper.getInstance()._toast("请填收货地址");
            return;
        } else if (phone.length() != 11) {
            ToastHelper.getInstance()._toast("联系电话格式错误");
            return;
        } else if (username.getText().toString().length() > 6) {
            ToastHelper.getInstance()._toast("姓名过长");
            return;
        }
        dlgLoading = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dlgLoading.show();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("addressID", addressID);
        map.put("consignee", username.getText().toString());
        map.put("phone", phone.getText().toString());
        map.put("province", mprovince);
        map.put("city", mcity);
        map.put("district", mdistrict);
        map.put("address", address.getText().toString());
        map.put("isDefault", isDefault);
        saveAddress(map, JSONRequest.PUT, Constant.ADDRESS_EDIT_URL);
    }

    /**
     * 设置默认地址
     *
     * @param view
     */
    public void setDefault(View view) {
        dlgLoading = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dlgLoading.show();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("addressID", addressID);
        map.put("isDefault", "1");
        saveAddress(map, JSONRequest.PUT, Constant.ADDRESS_SETDEFAULT_URL);
    }

    /**
     *
     */
    private void saveAddress(Map<String, Object> map, int type, String url) {
        JSONRequest.getInstance().sendRequest(type, url, map, handler, 1, HttpUtil.ACTION_JSON);
    }


    private void delAddress(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("{addressID}", id);
        JSONRequest.getInstance().sendRequest(JSONRequest.DELETE, Constant.ADDRESS_DELETE_URL, map, handler, 3, HttpUtil.ACTION_URI);

    }

    protected void dialog(final String id) {

        final ConfirmDialog dialog = new ConfirmDialog(EditAddressActivity.this, "温馨提示", "是否删除？", "取消", "确认");
        dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                dialog.dismiss();
            }

            @Override
            public void doRight() {
                delAddress(id);
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    protected void dialog1(final String id) {

        Builder builder = new Builder(EditAddressActivity.this);
        builder.setMessage("是否删除？");
        builder.setTitle("提示");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                delAddress(id);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }

        });
        builder.create().show();
    }
}
